import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:async/async.dart';
import 'package:flutter_appdemo02/list/chapterone.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';

class MyProfile extends StatefulWidget {
  @override
  _MyProfileState createState() => _MyProfileState();
}



List demo = [
  {
    "icon": Icons.person,
    "text": "My Info",
  },
  {
    "icon": FontAwesomeIcons.bed,
    "text": "My Bedroom",
  },
  {
    "icon": Icons.info,
    "text": "My Account",
  },
  {
    "icon": FontAwesomeIcons.heart,
    "text": "Interests",
  },
  {
    "icon": FontAwesomeIcons.instagram,
    "text": "Instagram",
  },
  {
    "icon": FontAwesomeIcons.spotify,
    "text": "Spotify",
  }
];

class _MyProfileState extends State<MyProfile> {
  TextEditingController _controller = TextEditingController();
  List<File> fileList = List();
  Future<File> _imageFile;
  bool isLoading = false;
  bool isSelect = true;
  String msg = "";

  Widget getBody() {
    // 输入框
    var textField = TextField(
      decoration: InputDecoration(
          hintText: "Enter your bio here...",
          hintStyle: TextStyle(
              color: const Color(0xFF808080),
              fontSize: 20,
              fontWeight: FontWeight.w700),
          border: OutlineInputBorder(
              borderRadius:
                  const BorderRadius.all(const Radius.circular(10.0)))),
      maxLines: 6,
      maxLength: 150,
      controller: _controller,
    );
    // gridView用来显示选择的图片
    var gridView = Builder(
      builder: (ctx) {
        return GridView.count(
          // 分4列显示
          crossAxisCount: 4,
          children: List.generate(fileList.length + 1, (index) {
            // 这个方法体用于生成GridView中的一个item
            var content;
            if (index == 0) {
              var addCell = Container(
                child: Center(
                  child: Icon(
                    Icons.add,
                    color: Colors.white,
                    size: 30,
                  ),
                ),
//                decoration: BoxDecoration(
//                  borderRadius: BorderRadius.circular(60)
//                ),
              );
              content = GestureDetector(
                onTap: () {
                  // 添加图片
                  pickImage(ctx);
                },
                child: addCell,
              );
            } else {
              // 被选中的图片
              content = GestureDetector(
                child: Center(
                    child: Image.file(
                  fileList[index - 1],
                  width: 80.0,
                  height: 80.0,
                  fit: BoxFit.cover,
                )),
                onTap: () {
                  /*showDialog(
                      context: context,
                      builder: (context) => AlertDialog(
                        title: Text("hello"),
                        actions: <Widget>[
                          new FlatButton(
                            child: new Text("确定"),
                            onPressed: () {
                              Navigator.of(context)
                                  .pop();
                            },
                          ),
                        ],
                      ));*/
                },
              );
            }
            return Container(
              margin: const EdgeInsets.all(2.0),
              width: 80.0,
              height: 80.0,
              color: const Color(0xFFECECee),
              child: content,
            );
          }),
        );
      },
    );
    var children = [
      Container(
        margin: const EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 0.0),
        height: 200.0,
        child: gridView,
      ),
      textField,
    ];
    if (isLoading) {
      children.add(Container(
        margin: const EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 0.0),
        child: Center(
          child: CircularProgressIndicator(),
        ),
      ));
    } else {
      children.add(Container(
          margin: const EdgeInsets.fromLTRB(0.0, 20.0, 0.0, 0.0),
          child: Center(
            child: Text(msg),
          )));
    }
    return Container(
      padding: const EdgeInsets.all(5.0),
      child: Column(
        children: children,
      ),
    );
  }

  // 相机拍照或者从图库选择图片
  pickImage(ctx) {
    // 如果已添加了9张图片，则提示不允许添加更多
    num size = fileList.length;
    if (size >= 5) {
      Scaffold.of(ctx).showSnackBar(SnackBar(
        content: Text("最多只能添加5张图片！"),
      ));
      return;
    }
    showModalBottomSheet<void>(context: context, builder: _bottomSheetBuilder);
  }

  Widget _bottomSheetBuilder(BuildContext context) {
    return Container(
        height: 182.0,
        child: Padding(
          padding: const EdgeInsets.fromLTRB(0.0, 30.0, 0.0, 30.0),
          child: Column(
            children: <Widget>[
              _renderBottomMenuItem("相机拍照", ImageSource.camera),
              Divider(
                height: 2.0,
              ),
              _renderBottomMenuItem("图库选择照片", ImageSource.gallery)
            ],
          ),
        ));
  }

  _renderBottomMenuItem(title, ImageSource source) {
    var item = Container(
      height: 60.0,
      child: Center(
          child: Text(
        title,
      )),
    );
    return InkWell(
      child: item,
      onTap: () {
        Navigator.of(context).pop();
        setState(() {
          _imageFile = ImagePicker.pickImage(source: source);
        });
      },
    );
  }




  sendTweet(ctx, token) async {
    // 未登录或者未输入动弹内容时，使用SnackBar提示用户
    if (token == null) {
      Scaffold.of(ctx).showSnackBar(SnackBar(
        content: Text("未登录！"),
      ));
      return;
    }
    String content = _controller.text;
    if (content == null || content.length == 0 || content.trim().length == 0) {
      Scaffold.of(ctx).showSnackBar(SnackBar(
        content: Text("Enter your bio here...！"),
      ));
    }
    // 下面是调用接口发布动弹的逻辑
    try {
      Map<String, String> params = Map();
      params['msg'] = content;
      params['access_token'] = token;
      // 构造一个MultipartRequest对象用于上传图片
      var request = http.MultipartRequest('POST', Uri.parse(""));
      request.fields.addAll(params);
      if (fileList != null && fileList.length > 0) {
        for (File f in fileList) {
          // 文件流
          var stream = http.ByteStream(DelegatingStream.typed(f.openRead()));
          // 文件长度
          var length = await f.length();
          // 文件名
          var filename = f.path.substring(f.path.lastIndexOf("/") + 1);
          // 将文件加入到请求体中
          request.files.add(
              http.MultipartFile('img', stream, length, filename: filename));
        }
      }
      setState(() {
        isLoading = true;
      });
      // 发送请求
      var response = await request.send();
      // 解析请求返回的数据
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
        if (value != null) {
          var obj = json.decode(value);
          var error = obj['error'];
          setState(() {
            if (error != null && error == '200') {
              // 成功
              setState(() {
                isLoading = false;
                msg = "发布成功";
                fileList.clear();
              });
              _controller.clear();
            } else {
              setState(() {
                isLoading = false;
                msg = "发布失败：$error";
              });
            }
          });
        }
      });
    } catch (exception) {
      print(exception);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Center(
            child: Text(
              "My Profile",
              textAlign: TextAlign.center,
              style: TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.w800,
                  fontSize: 24),
            ),
          ),
          backgroundColor: Colors.white,
          elevation: 0,
          actions: <Widget>[
            RaisedButton(
              child: Text(
                '完成',
                style: TextStyle(
                    color: Colors.deepPurple,
                    fontWeight: FontWeight.w700,
                    fontSize: 19),
              ),
              onPressed: () {},
              color: Colors.white,
              elevation: 0,
            ),
          ],
        ),
        body: CustomScrollView(shrinkWrap: true, slivers: <Widget>[
          SliverPadding(
            padding: const EdgeInsets.all(10.0),
            sliver: SliverList(
              delegate: SliverChildListDelegate(<Widget>[
                /*FutureBuilder(
                  future: _imageFile,
                  builder:
                      (BuildContext context, AsyncSnapshot<File> snapshot) {
                    if (snapshot.connectionState == ConnectionState.done &&
                        snapshot.data != null &&
                        _imageFile != null) {
                      // 选择了图片（拍照或图库选择），添加到List中
                      fileList.add(snapshot.data);
                      _imageFile = null;
                    }
                    // 返回的widget
                    return getBody();
                  },
                ),*/

                Padding(
                  padding: EdgeInsets.all(4),
                  child: Row(
                    children: <Widget>[
                      Container(
                        width: MediaQuery.of(context).size.width / 2.5,
                        child: Stack(
                          children: <Widget>[
                            Padding(
                              padding: EdgeInsets.all(4),
                              child: Container(
                                  height: 160,
                                  child: Container(),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(10),
                                      color: Colors.grey,
                                      image: DecorationImage(
                                          image: NetworkImage(
                                            "http://pics.sc.chinaz.com/files/pic/pic9/201904/zzpic17511.jpg",
                                          ),
                                          fit: BoxFit.cover))),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 130, top: 135),
                              child: CircleAvatar(
                                child: Icon(
                                  Icons.close,
                                  color: Colors.white,
                                ),
                                backgroundColor: Colors.deepPurple,
                              ),
                            )
                          ],
                        ),
                      ),
                      Container(
                          margin: EdgeInsets.only(left: 20),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Column(
                                children: <Widget>[
                                  _card,
                                  _card,
                                ],
                              ),
                              Column(
                                children: <Widget>[
                                  _card,
                                  _card,
                                ],
                              ),
                            ],
                          ))
                    ],
                  ),
                ),
                Container(
                  child: TextField(
                    decoration: InputDecoration(
                        hintText: "Enter your bio here...",
                        hintStyle: TextStyle(
                            color: const Color(0xFF808080),
                            fontSize: 20,
                            fontWeight: FontWeight.w700),
                        border: OutlineInputBorder(
                            borderRadius: const BorderRadius.all(
                                const Radius.circular(10.0)))),
                    maxLines: 6,
                    maxLength: 150,
                    controller: _controller,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 15),
                  child: Text(
                    "Profile Completion 55%",
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.w700,
                    ),
                  ),
                ),
                Stack(
                  children: <Widget>[
                    Container(
                      height: 10,
                      margin: EdgeInsets.only(top: 10, left: 15, right: 15),
                      decoration: BoxDecoration(
                          color: Colors.grey,
                          borderRadius: BorderRadius.circular(30)),
                    ),
                    Container(
                      height: 10,
                      width: 200,
                      margin: EdgeInsets.only(top: 10, left: 15, right: 15),
                      decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [
                              Colors.purpleAccent,
                              Colors.deepPurpleAccent
                            ],
                            begin: Alignment.bottomLeft,
                            end: Alignment.bottomRight,
                          ),
                          borderRadius: BorderRadius.circular(30)),
                    )
                  ],
                ),
                GestureDetector(
                  child: Container(
                    margin: EdgeInsets.all(10),
                    height: 60,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Center(
                          child: Icon(
                            Icons.photo_camera,
                            color: Colors.white,
                          ),
                        ),
                        Center(
                          child:
//                          _renderBottomMenuItem("Verify Your Photos",ImageSource.camera)

                              Text(
                            "Verify Your Photos",
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        )
                      ],
                    ),
                    decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [Colors.deepPurpleAccent, Colors.deepPurple],
                          begin: Alignment.bottomLeft,
                          end: Alignment.bottomRight,
                        ),
                        borderRadius: BorderRadius.circular(15)),
                  ),
                  onTap: () {
                    showDialog(
                        context: context,
                        builder: (context) => AlertDialog(
                              title: Text("Verify Your Photos"),
                              actions: <Widget>[
                                new FlatButton(
                                  child: new Text("确定"),
                                  onPressed: () {
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ],
                            ));
                  },
                )
              ]),
            ),
          ),
          SliverPadding(
            padding: EdgeInsets.all(14),
            sliver: SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2, //一行多少个
                ),
                delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                    return Card(
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Container(
                              height: 130,
                              padding: EdgeInsets.only(
                                  right: 30, left: 30, top: 30, bottom: 10),
                              child: Icon(
                                demo[index]["icon"],
                                size: 50,
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.only(bottom: 20),
                              child: Text(
                                demo[index]["text"],
                                style: TextStyle(
                                  fontSize: 20,
                                  fontWeight: FontWeight.w700,
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    );
                  },
                  childCount: chapterone.length,
                )),
          )
        ]));
  }
}

Widget _card = Card(
  child: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          height: 76,
          width: 76,
          child: Icon(
            Icons.add,
            size: 40,
          )
//          Image.network("http://pics.sc.chinaz.com/files/pic/pic9/201811/zzpic14991.jpg",fit: BoxFit.cover,)
          ,
        ),
      ],
    ),
  ),
);
